package com.yikaiye.android.yikaiye.ui.activity.order;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.base.BaseViewModel;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityFaDaDaBinding;
import com.yikaiye.android.yikaiye.dialog.ChoosePhotoDialog;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.utils.ToastHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class FaDaDaActivity extends BaseActivity<ActivityFaDaDaBinding, BaseViewModel> {

    private Uri imageUri;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int PHOTO_REQUEST = 1000;
    public static final int TAKE_PICK = 1001;
    private ChoosePhotoDialog choosePhotoDialog;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initWebView();
        initDialog();
        if (getIntent().getExtras() != null) {
            String url = getIntent().getExtras().getString(Constant.URL_KEY);
            if (!TextUtils.isEmpty(url)) {
                binding.webView.loadUrl(url);
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void initWebView() {
        WebSettings settings = binding.webView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowContentAccess(true);
        // 是否可访问本地文件，默认值 true
        settings.setAllowFileAccess(true);
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        settings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        settings.setAllowUniversalAccessFromFileURLs(false);
        //开启JavaScript支持
        settings.setJavaScriptEnabled(true);
        // 支持缩放
        settings.setSupportZoom(true);
        //辅助WebView设置处理关于页面跳转，页面请求等操作
//        binding.webView.setWebViewClient(new MyWebViewClient());
        //辅助WebView处理图片上传操作
        binding.webView.setWebChromeClient(new MyChromeWebClient());
        binding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, final String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                Log.e("onPageStarted", s + "=");
                if (s != null && s.contains("callback/return")) {
                    if (s.contains("signContract")) {
                        ToastHelper.show(getString(R.string.sign_success));
                        EventBus.getDefault().post(new EventBusModel(Constant.signSuccess));
                        FaDaDaActivity.this.finish();
                    } else if (s.contains("identityVerify")) {
                        ToastHelper.show(getString(R.string.real_name_success));
                        FaDaDaActivity.this.finish();
                    }
                }
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }
        });

    }

    /**
     * 自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
     */
    public class MyChromeWebClient extends WebChromeClient {
        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            choosePhotoDialog.showDialog();
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            choosePhotoDialog.showDialog();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                binding.progressBar.setVisibility(View.GONE);
            } else {
                binding.progressBar.setVisibility(View.VISIBLE);
                binding.progressBar.setProgress(newProgress);
            }
        }
    }

    /**
     * 包含拍照和相册选择
     */
    public void initDialog() {
        choosePhotoDialog = new ChoosePhotoDialog(this) {
            @Override
            public void chooseOne() {
                if (!XXPermissions.isGrantedPermission(context, Permission.MANAGE_EXTERNAL_STORAGE)) {
                    XXPermissions.with(context)
                            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                            .request((permissions, all) -> imagePick());
                } else {
                    imagePick();
                }
            }

            @Override
            public void chooseTwo() {
                if (!XXPermissions.isGrantedPermission(context, Permission.CAMERA)) {
                    XXPermissions.with(context)
                            .permission(Permission.CAMERA)
                            .request((permissions, all) -> takePhoto());
                } else {
                    takePhoto();
                }
            }
        };
    }

    /**
     * 相册
     */
    private void imagePick() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, TAKE_PICK);
    }

    private void takePhoto() {
        File outputImage = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = FileProvider.getUriForFile(this,
                Constant.APP_PROVIDER, outputImage);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, PHOTO_REQUEST);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果按下的是回退键且历史记录里确实还有页面
        if ((keyCode == KeyEvent.KEYCODE_BACK) && binding.webView.canGoBack()) {
            binding.webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST || requestCode == TAKE_PICK) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
    }

    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST || requestCode == TAKE_PICK) {
            if (mUploadCallbackAboveL == null) return;
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    results = new Uri[]{imageUri};
                } else {
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }

                    if (dataString != null)
                        results = new Uri[]{Uri.parse(dataString)};
                }
            }
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.webView.setWebViewClient(null);
        binding.webView.setWebChromeClient(null);
        binding.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        binding.webView.clearHistory();
        binding.webView.destroy();
    }

    @Override
    public void onBackPressed() { // do nothing
        if (binding.webView.canGoBack()) {
            binding.webView.goBack();
        } else {
            finish();
        }
    }
}